package jms;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NamedThreadFactory implements ThreadFactory {
	private final String name;
	private final AtomicInteger counter = new AtomicInteger(0); 
	
	public NamedThreadFactory(String name) {
		if(name == null)
			throw new NullPointerException("name");
		this.name = name;
	}
	
	public Thread newThread(Runnable runner) {
		Thread thread = new Thread(runner);
		thread.setName(name + counter.getAndIncrement());
		
		thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
			
			public void uncaughtException(Thread th, Throwable ex) {
				Logger.getAnonymousLogger().log(Level.SEVERE, "", ex);
			}
		});
		
		return thread;
	}

}
